import * as echarts from '../../components/ec-canvas/echarts';
const app = getApp();

//保存拼图实例
let chartInstance= null;
Page({

    /**
     * 页面的初始数据
     */
    data: {

        mainType: [{
            type: 'sr',
            title: '收入',
            total: '0.00'
        },
        {
            type: 'zc',
            title: '支出',
            total: '0.00'
        }
        ],

        activeIndex: 0,

        textArray: ['年', '月', '日'],

        text: '',

        textIndex: 0,

        date: '选择日期',

        //用户选择的日期
        userDate: '',

        //大月
        largeMonth: ['01', '03', '05', '07', '08', '10', '12'],

        //picker的日期范围
        start: '',
        end: '',

        //保存记账数据(包含收入-支出)
        bookingDatas: {},
        ec: {
            onInit: null
        }
    },

    //初始化的canvas实例
    initChart(canvas, width, height, dpr){
        const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr // new
        });
        canvas.setChart(chart);
       
        //绘制
        // chart.setOption(option);

        chartInstance = chart
        return chart;

        
    },



    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            text: this.data.textArray[this.data.textIndex]
        })

        let currentDate = this.getCurrentDate();
        this.setDate(currentDate);

        this.setData({
            userDate: currentDate,
            start: app.globalData.start,
            end: currentDate,
            ec: {
                onInit: this.initChart
            }
        })

        this.getBookingDataByDateRange(currentDate);
    },

    //获取当前的日期 yyyy-MM-dd
    getCurrentDate() {
        //获取当前日期
        let currentDate = new Date();
        let year = currentDate.getFullYear();
        let month = currentDate.getMonth() + 1;
        month = month >= 10 ? month : '0' + month;
        let date = currentDate.getDate();
        date = date >= 10 ? date : '0' + date;

        return `${year}-${month}-${date}`;
    },

    //切换收入和支出状态
    toggleMainTypeStatus(e) {
        let index = e.currentTarget.dataset.index;
        if (index === this.data.activeIndex) {
            return;
        }

        this.setData({
            activeIndex: index
        })

   

          //绘制拼图
          this.drawPie()
    },

    //切换年月日
    toggle() {
        let length = this.data.textArray.length;
        if (this.data.textIndex === length - 1) {
            this.data.textIndex = 0;

        } else {
            this.data.textIndex++;
        }

        this.setData({
            text: this.data.textArray[this.data.textIndex]
        })

        this.setDate(this.data.userDate);

        this.getBookingDataByDateRange(this.data.userDate);
    },

    //设置日期
    setDate(currentDate) {
        let date = currentDate.split('-');
        let d = date.slice(0, this.data.textIndex + 1);
        // 

        let dateArray = [];
        d.forEach((v, i) => {
            dateArray.push(`${v}${this.data.textArray[i]}`)
        })

        

        this.setData({
            date: dateArray.join('')
        })
    },

    //选择日期
    selectDate(e) {
        let currentDate = e.detail.value;
        
        this.setDate(currentDate);
        this.setData({
            userDate: currentDate
        })

        this.getBookingDataByDateRange(currentDate);
    },

    //随机生成颜色
    createRandomColor() {
        //0-255
        let rgb = [];
        for (let i = 0; i < 3; i++) {
            let value = Math.ceil(Math.random() * 255);
            rgb.push(value);
        }

        return `rgb(${rgb.join(',')})`;
    },

    //根据日期范围查询记账数据
    getBookingDataByDateRange(date) {
        

        //日期范围
        let start = '';
        let end = '';

        //获取当前日期
        let crrentDate = this.getCurrentDate().split('-');
        date = date.split('-');
        
        

        //按年查询
        if (this.data.textIndex === 0) {
            

            start = `${date[0]}-01-01`;

            //如果同年
            if (crrentDate[0] === date[0]) {
                end = crrentDate.join('-')
            } else {
                //如果不同年
                end = `${date[0]}-12-31`;
            }

        } else if (this.data.textIndex === 1) {
            

            start = `${date[0]}-${date[1]}-01`;

            //如果同年
            if (crrentDate[0] === date[0]) {
                //如果同月
                if (crrentDate[1] === date[1]) {
                    end = date.join('-');
                } else {
                    //如果不同月
                    //如果是2月份
                    if (date[1] === '02') {
                        //如果闰年
                        if (date[0] % 400 === 0 || (date[0] % 4 === 0 && date[0] % 100 !== 0)) {
                            end = `${date[0]}-02-29`;
                        } else {
                            end = `${date[0]}-02-28`;
                        }
                    } else {
                        //如果不是2月份
                        //如果是大月
                        if (this.data.largeMonth.indexOf(date[1]) > -1) {
                            end = `${date[0]}-${date[1]}-31`;
                        } else {
                            end = `${date[0]}-${date[1]}-30`;
                        }
                    }
                }
            } else {
                //如果不同年
                //如果不同月
                //如果是2月份
                if (date[1] === '02') {
                    //如果闰年
                    if (date[0] % 400 === 0 || (date[0] % 4 === 0 && date[0] % 100 !== 0)) {
                        end = `${date[0]}-02-29`;
                    } else {
                        end = `${date[0]}-02-28`;
                    }
                } else {
                    //如果不是2月份
                    //如果是大月
                    if (this.data.largeMonth.indexOf(date[1]) > -1) {
                        end = `${date[0]}-${date[1]}-31`;
                    } else {
                        end = `${date[0]}-${date[1]}-30`;
                    }
                }
            }

        } else {
            
            start = date.join('-');
        }

        
        

        wx.showLoading({
            title: '加载中...',
            mask: true
        })

        let data = {
            start
        };

        if (end) {
            data.end = end;
        }

        // return;

        //调用云端的云函数
        wx.cloud.callFunction({
            //云端的云函数名称
            name: 'get_booking_bydateRange',
            data,
        }).then(res => {
            //关闭加载提示
            wx.hideLoading();

            

            //按收入-支出分类
            /**
             * [
             *    {
             *      type: 'sr',
             *      total: 0,
             *      subTypes: [
             *        {
             *          type: 'canyin',
             *          title: '餐饮',
             *          total: 0,
             *          icon: '',
             *          data: [
             *            {餐饮类型1},
             *            {餐饮类型2},
             *          ]
             *        },
             *        {...},
             *        {...}
             *      ]
             *    },
             *    {
             *      ....
             *    }
             * ]
             */

            let mainType = ['sr', 'zc'];

            let datas = {};

            //查询指定的类型数据
            mainType.forEach((v, i) => {
                let data = {
                    type: v,
                    total: 0,
                    subTypes: []
                };

                res.result.data.forEach(item => {
                    if (v === item.mainType.type) {
                        data.subTypes.push(item);
                        data.total += Number(item.money);
                    }
                })

                datas[v] = data;

                this.data.mainType[i].total = data.total.toFixed(2);
            })



            //按照收入-支出分类子类型(餐饮、交通、人情....)

            for (let key in datas) {
                let v = datas[key];

                //获取子类型数据
                let subTypes = v.subTypes;

                //子类型
                let sType = [];

                subTypes.forEach(item => {
                    if (sType.indexOf(item.subType.type) === -1) {
                        sType.push(item.subType.type);
                    }
                })


                //分类子类型
                let sTypeDatas = [];
                sType.forEach(value => {
                    let sty = {
                        //当前子类型的总金额
                        total: 0,
                        //当前子类型的笔数
                        count: 0,
                        //当前子类型的类型
                        type: value,

                        //子类型的标题
                        title: '',

                        //子类型的图标
                        pic: '',

                        //随机颜色
                        color: '',

                        //主类型(sr-zc)
                        mType: key,

                        //子类型
                        data: [],

                        //记账的_id
                        _ids:[],

                        //饼图data数据字段
                        name:'',

                        //饼图data数据name字段
                        value:0

                    };
                    subTypes.forEach(val => {
                        if (value === val.subType.type) {
                            sty.total += Number(val.money);
                            sty.count++;
                           
                            sty.data.push(val);
                            sty._ids.push(val._id);
                            sty.value += Number(val.money);
                            if (!sty.title) {
                                sty.title = val.subType.title;
                            }

                            if (!sty.pic) {
                                sty.pic = val.subType.pic;
                            }

                            if (!sty.color) {
                                sty.color = this.createRandomColor();
                            }

                            if(!sty.name){
                                sty.name = val.subType.title
                            }
                        }
                    })

                    sty.total = sty.total.toFixed(2);
                    sty.name += '' + (sty.value / v.total *100 ).toFixed(2)+'%'
                    sty._ids = sty._ids.join('-')
                    sTypeDatas.push(sty)
                })
                

                

                v.subTypes = sTypeDatas;

            }

            // datas.forEach(v => {



            // })


            

            // this.data.bookingDatas = datas;

            //设置收入和支出的总金额
            this.setData({
                mainType: this.data.mainType,
                bookingDatas: datas
            })

            //获取激活类型的数据(收入-支出)

            

            //绘制拼图
            this.drawPie()

        }).catch(err => {
            
        })

    },

    //绘制拼图
    drawPie(){
        //data 拼图数据 ,Array,[{name:'a',value:10}.....]
        //color 区域块的颜色,Array,['颜色1'...]

        //获取颜色
        let colors = [];
        let subTypeData = this.data.bookingDatas[this.data.mainType[this.data.activeIndex].type].subTypes;
        subTypeData.forEach(v=>{
            colors.push(v.color)
        })

        //  配置
        var option = {
            backgroundColor: "#ffffff",
            color:colors,
            title: {
                text: ""
            },
            legend: {
                bottom: '1%'
            },
            series: [{
                label: {
                    normal: {
                        fontSize: 14
                    }
                },
                type: 'pie',
                center: ['50%', '50%'],
                radius: '50%',
                itemStyle: {
                    borderRadius: 100
                },
                data:subTypeData
            }]
        };

        chartInstance.setOption(option)
    },

    //查看记账详情
    viewBookingDetail(e){
        let _ids = e.currentTarget.dataset._ids;

        wx.navigateTo({
          url: `../bookingDetail/bookingDetail?_ids=${_ids}`,
        })
    }
})